package com.kalvin.kvf.modules.sys.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.kalvin.kvf.common.controller.BaseController;
import com.kalvin.kvf.common.dto.R;
import com.kalvin.kvf.common.utils.ShiroKit;
import com.kalvin.kvf.modules.sys.dto.wx.WxPayConfig;
import com.kalvin.kvf.modules.sys.entity.User;
import com.kalvin.kvf.modules.sys.service.IMenuService;
import com.kalvin.kvf.modules.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@RestController
public class IndexController extends BaseController {

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IUserService userService;


    // 微信支付查询 参数是订单id
    @RequestMapping("/paySearch")
    public Map paySearch(String id) throws Exception {

            // 处理参数
            WxPayConfig wxPayConfig = new WxPayConfig();
            WXPay wxPay = new WXPay(wxPayConfig);
            Map<String,String> data = new HashMap<>();
            data.put("out_trade_no", id);   //订单编号
            data.put("appid",wxPayConfig.getAppID());
            data.put("mch_id",wxPayConfig.getMchID());
            data.put("nonce_str", WXPayUtil.generateNonceStr());
            // 签名
            String s = WXPayUtil.generateSignature(data, wxPayConfig.getKey());
            data.put("sign",s);
            // 发起查询
            Map<String, String> result = wxPay.orderQuery(data);

            // 如果用户已支付
            if (result.get("return_code").equals("SUCCESS") && result.get("result_code").equals("SUCCESS") && result.get("trade_state").equals("SUCCESS")) {
                // 修改订单支付状态和支付id
            }
            return result;

    }



    @GetMapping(value = "/")
    public ModelAndView index() {
        User user = userService.getById(ShiroKit.getUserId());
        return new ModelAndView("index").addObject("authUserInfo", user);
    }

    @GetMapping(value = "home")
    public ModelAndView home() {
        return new ModelAndView("home");
    }

    @GetMapping(value = "test")
    public ModelAndView test() {
        return new ModelAndView("test");
    }

    @GetMapping(value = "index/menus")
    public R menus() {
        return R.ok(menuService.listUserPermissionMenuWithSubByUserId(ShiroKit.getUserId()));
    }

    @GetMapping(value = "index/navMenus")
    public R navMenus() {
        return R.ok(menuService.listUserPermissionNavMenuByUserId(ShiroKit.getUserId()));
    }

}
